<?php
use Workerman\Worker;
require_once __DIR__ . '/Workerman/Autoloader.php';

// 注意：这里与上个例子不同，使用的是websocket协议
$worker = new Worker("websocket://0.0.0.0:2000");

// 启动4个进程对外提供服务
$worker->count = 1;
$worker->uidConnections = array();
// 当收到客户端发来的数据后返回hello $data给客户端
$worker->onMessage = function($connection, $data)
{
    $connection->lastMessageTime = time();
    $info = json_decode($data,true);
    if (!isset($connection->uid)) {
        // 没验证的话把第一个包当做uid（这里为了方便演示，没做真正的验证）
        if (!empty($info)) {
            $user_id = M('UserToken')->getUserIdByAccessToken($info['access_token']);
            $connection->uid = $user_id;
            $worker->uidConnections[$info['id']][$connection->uid] = $connection;
        }else {
        }
    }else {
        foreach($worker->uidConnections[$info['id']] as $val)
        {
            if ($val->uid !=  $connection->uid) {
                $val->send($data);
            }
        }
    }
};
$worker->onWorkerStart = function ($worker) {
    \Workerman\Lib\Timer::add(1, function()use($worker){
        $time_now = time();
        foreach($worker->connections as $connection) {
            // 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
            if (empty($connection->lastMessageTime)) {
                $connection->lastMessageTime = $time_now;
                continue;
            }
            // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
            if ($time_now - $connection->lastMessageTime > 60) {
                $connection->close();
            }
        }
    });
};

// 运行worker
Worker::runAll();